package com.anjubao.parking.municipal.common.global;

import java.util.Map;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import com.google.common.collect.Maps;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class CustomConverterFactory implements ConverterFactory<String, BaseEnum> {

	private static final Map<Class<? extends BaseEnum>, Converter> converterMap = Maps.newConcurrentMap();

	@Override
	public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
		Converter<String, T> converter = converterMap.get(targetType);
		if (converter == null) {
			converter = new CodeConverterToEnum<>(targetType);
			converterMap.put(targetType, converter);
		}
		return converter;
	}

	class CodeConverterToEnum<T extends BaseEnum> implements Converter<String, T> {
		private Map<String, T> enumMap = Maps.newHashMap();

		public CodeConverterToEnum(Class<T> enumType) {
			T[] enums = enumType.getEnumConstants();
			for (T e : enums) {
				enumMap.put(String.valueOf(e.getCode()), e);
			}
		}

		@Override
		public T convert(String source) {
			return enumMap.get(source);
		}
	}

}
